<?php
include_once "conn.php";
include_once "dealFile.php";
$token=$_POST['token']; //获取用户信息
$sql = $db -> query("SELECT user_icon,user_id FROM user WHERE user_token = '$token'"); //查询id,图标地址
// 删除原来的头像，并删除数据库存储的地址
$row = $sql -> fetch_assoc(); //输出结果
$icon = substr($row['user_icon'],25); //截取相对路径
$cut = substr($row['user_id'],5); //截取用户id的一部分
$dir='pic/user_icon/icon'.$cut.'-'.$time.'.jpeg'; //移动到的文件目录
$url='http://120.77.18.178/api/'.$dir; //插入数据表的路径
$uploadFile = move_uploaded_file($_FILES["file"]["tmp_name"],$dir); 
if($uploadFile){
    if(file_exists($icon)){ //如果原来存在icon
        if(unlink($icon)){
            $db->query("UPDATE user SET user_icon = '$url' WHERE user_token = '$token'");
            echo json_encode(['state'=>'suc','reason'=>'origin_delete_suc']);
        }else{ //删除原来的文件失败,则删除刚上传的文件;
            unlink($dir);
            echo json_encode(['state'=>'err','reason'=>'origin_delete_err']);
        }
    }else{ //y原来不存在icon或者没有找到
        $db->query("UPDATE user SET user_icon = '$url' WHERE user_token = '$token'");
        echo json_encode(['state'=>'suc','reason'=>'origin_no_exist']);
    }
}else{
    echo json_encode(['state'=>'err','reason'=>'upload_err']);
}

$db->close();
?>